﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;

namespace TravelSite.Controls
{
    public partial class ContractVerify : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void LoadView(int contractId)
        {
            int travelId;
            int clientId;

            using (var repo = RepositoryFactory.ResolveRepository<ContractRepository>())
            {
                Contract item = repo.Find(contractId);
                if (!item.TravelId.HasValue)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", "alert('No Travel Available!');", true);
                    return;
                }
                else
                {
                    clientId = item.ContactId;
                    travelId = item.TravelId.Value;
                    btnClear.Visible = item.PackageStatus == "PENDING";
                    btnBooked.Visible = item.PackageStatus == "PENDING" || item.PackageStatus == "BOOKED";
                    AllowOverride =  item.PackageStatus == "PENDING" || item.PackageStatus == "BOOKED";

                    if (item.PackageStatus == "CANCELED")
                    {
                        btnClear.Visible = true;
                        btnClear.Text = "Reactivate";

                        btnCanceled.Visible = false;
                    }
                }
            }

            hdContractId.Text = contractId.ToString();
            hdTravelId.Text = travelId.ToString();

            using (var repo = RepositoryFactory.ResolveRepository<ApiTravelPackageRepository>())
            {
                TravelPackage clientPackage = repo.FindClientPackage(travelId);
                lblPackage.Text = clientPackage.PackageName;
                lblTravelDate.Text = (clientPackage.StartDate.HasValue ? clientPackage.StartDate.Value.ToString("d") : "") +
                    " - " + (clientPackage.EndDate.HasValue ? clientPackage.EndDate.Value.ToString("d") : "");

                if (clientPackage.PkgDestId > 0)
                {
                    PackageDestination pDest = repo.FindDestination(clientPackage.PkgDestId);
                    lblPackageDestination.Text = pDest.DestinationName;
                }
                else
                    lblPackageDestination.Text = "NO DESTINATION";


                var options = repo.FindOptions(clientPackage.PkgDestId, travelId);
                grid.DataSource = options.Where(i => i.SelectedChoiceId != -1);
                grid.DataBind();
            }
        }

        protected void upVerify_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["__EVENTTARGET"]))
                if (Request["__EVENTTARGET"] != upVerify.ClientID)
                    return;

            if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
            {
                LoadView(Convert.ToInt32(Request["__EVENTARGUMENT"]));                
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowEdit", "openVerify();", true);
            }
        }

        protected void grid_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                PackageDestinationOption item = (PackageDestinationOption)e.Item.DataItem;

                Label lbl = (Label)e.Item.FindControl("lblOptionChoice");
                lbl.Text = item.Choices.Where(i => i.ChoiceId == item.SelectedChoiceId).Single().ClientChoiceDescription;

                ImageButton lbOverride = (ImageButton)e.Item.FindControl("lbOverride");
                lbOverride.Visible = AllowOverride;

            }
        }

        protected void grid_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());
            Label lblOptionChoice = (Label)e.Item.FindControl("lblOptionChoice");
            TextBox tbOverrideChoice = (TextBox)e.Item.FindControl("tbOverrideChoice");
            ImageButton lbOverride = (ImageButton)e.Item.FindControl("lbOverride");
            switch (e.CommandName)
            {
                case "override":
                    lblOptionChoice.Visible = false;
                    tbOverrideChoice.Visible = true;
                    tbOverrideChoice.Text = lblOptionChoice.Text;
                    break;
            }

        }

        protected void btnBooked_Click(object sender, EventArgs e)
        {
            int contractId = Convert.ToInt32(hdContractId.Text);
            int travelId = Convert.ToInt32(hdTravelId.Text);

            Contract ctr = null;
            Contact ct = null;
            string contactEmail;

            string choiceIdList = "";
            string overrideChoiceList = "";
            foreach (RepeaterItem ri in grid.Items)
            {
                TextBox tbOverrideChoice = (TextBox)ri.FindControl("tbOverrideChoice");
                if (tbOverrideChoice.Visible)
                {
                    choiceIdList += ((HiddenField)ri.FindControl("hidId")).Value + ";";
                    overrideChoiceList += tbOverrideChoice.Text + ";";
                }
            }

            using (var repo = RepositoryFactory.ResolveRepository<ContractRepository>())
            {
                repo.SetBooked(contractId, choiceIdList, overrideChoiceList);
                ctr = repo.Find(contractId);
            }
            
            using (ContactRepository repo = new ContactRepository())
            {
                ct = repo.Find(ctr.ContactId);
                contactEmail = ct.Email;
            }

            if (!string.IsNullOrEmpty(contactEmail))
            {
                string temlatePath = Server.MapPath("~/Files/System/BookedPackage.html");
                string msgBody = File.ReadAllText(temlatePath);

                msgBody = msgBody.Replace("%FirstName%", ct.FirstName);
                msgBody = msgBody.Replace("%LastName%", ct.LastName);

                using (var repo = RepositoryFactory.ResolveRepository<ApiTravelPackageRepository>())
                {
                    TravelPackage clientPackage = repo.FindClientPackage(travelId);
                    
                    msgBody = msgBody.Replace("%PackageName%", clientPackage.PackageName);
                    msgBody = msgBody.Replace("%TravelDates%", 
                        string.Format("Travel dates: {0}",
                        (clientPackage.StartDate.HasValue ? clientPackage.StartDate.Value.ToString("d") : "") +
                        " - " + (clientPackage.EndDate.HasValue ? clientPackage.EndDate.Value.ToString("d") : ""))); 
                                        
                    PackageDestination pDest = repo.FindDestination(clientPackage.PkgDestId);
                    msgBody = msgBody.Replace("%Destination%", "Destination: " + pDest.DestinationName);

                    var optionsList = repo.FindOptions(clientPackage.PkgDestId, travelId).Where(i => i.SelectedChoiceId != -1).ToList();
                    string optionsString = "";
                    foreach (PackageDestinationOption pdo in optionsList)
                        optionsString += string.Format("{0}: {1}<br/>", pdo.OptionName, pdo.Choices.Where(i => i.ChoiceId == pdo.SelectedChoiceId).Single().ClientChoiceDescription);
                    msgBody = msgBody.Replace("%Options%", optionsString);
                }

                try
                {
                    Common.SendEmail(contactEmail, "", "Package confirmed", msgBody);
                }
                catch (Exception ex)
                {
                }
            }
            
            LoadView(Convert.ToInt32(hdContractId.Text));
            (this.Page as BaseDataPage).LoadData();
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            int contractId = Convert.ToInt32(hdContractId.Text);
            int travelId = Convert.ToInt32(hdTravelId.Text);

            Contract ctr = null;
            Contact ct = null;
            string contactEmail;
            string pin;

            using (var repo = RepositoryFactory.ResolveRepository<ContractRepository>())
            {
                repo.SetClear(contractId);
                ctr = repo.Find(contractId);
            }

            using (ContactRepository repo = new ContactRepository())
            {
                ct = repo.Find(ctr.ContactId);
                contactEmail = ct.Email;
            }

            using (ApiContactRepository repo = new ApiContactRepository())
            {
                pin = repo.GetPin(ct.ContactId);
            }

            if (!string.IsNullOrEmpty(contactEmail))
            {
                string temlatePath = Server.MapPath("~/Files/System/ClearPackage.html");
                string msgBody = File.ReadAllText(temlatePath);

                msgBody = msgBody.Replace("%FirstName%", ct.FirstName);
                msgBody = msgBody.Replace("%LastName%", ct.LastName);
                msgBody = msgBody.Replace("%Pin%", pin);

                using (var repo = RepositoryFactory.ResolveRepository<ApiTravelPackageRepository>())
                {
                    TravelPackage clientPackage = repo.FindClientPackage(travelId);
                    msgBody = msgBody.Replace("%PackageName%", clientPackage.PackageName);
                }

                try
                {
                    Common.SendEmail(contactEmail, "", "Package cancel", msgBody);
                }
                catch (Exception ex)
                {
                }
            }

            LoadView(Convert.ToInt32(hdContractId.Text));
            (this.Page as BaseDataPage).LoadData();
        }

        protected void btnCanceled_Click(object sender, EventArgs e)
        {
            int contractId = Convert.ToInt32(hdContractId.Text);
            
            using (var repo = RepositoryFactory.ResolveRepository<ContractRepository>())
            {
                repo.SetCanceled(contractId);
            }

            LoadView(Convert.ToInt32(hdContractId.Text));
            (this.Page as BaseDataPage).LoadData();
        }

        private bool AllowOverride
        {
            get
            {
                if (this.ViewState["AllowOverride"] == null)
                    return false;
                return this.ViewState["AllowOverride"].ToString() == "1";
            }
            set
            {
                this.ViewState["AllowOverride"] = value?"1":"0";
            }
        }
    }
}